﻿using System.Collections.Generic;
using System.Web.Mvc;
using Common;
using ForumEngine.Models;
using ForumEngine.Routing;
using ViewServices;

namespace ForumEngine.Controllers
{
    public class ForumController : Controller
    {
        private readonly IForumViewService _forumViewService;
        private readonly IPathViewService _pathViewService;

        public ForumController(IForumViewService forumViewService, IPathViewService pathViewService)
        {
            _forumViewService = forumViewService;
            _pathViewService = pathViewService;
        }

        private UrlHelper UrlHelper
        {
            get { return new UrlHelper(ControllerContext.RequestContext); }
        }

        public ViewResult Index()
        {
            var sections = _forumViewService.GetAllSections();

            return View("Sections", new SectionListModel
            {
                Sections = sections,
                Path = new List<PathModel> { _pathViewService.GetPathRoot(), _pathViewService.GetPathSections() }
            });
        }

        public ActionResult Thread(long id, string page)
        {
            if (string.IsNullOrEmpty(page))
            {
                return Redirect(UrlHelper.RouteAction(Constants.Applications.Forum.Name, Constants.Applications.Forum.Actions.Thread, id, 1));
            }

            if (page == "last")
            {
                return Redirect(UrlHelper.RouteAction(Constants.Applications.Forum.Name, Constants.Applications.Forum.Actions.Thread, id, _forumViewService.GetThreadLastPage(id)));
            }

            int pageNumber;
            if (!int.TryParse(page, out pageNumber))
            {
                return Redirect(UrlHelper.RouteAction(Constants.Applications.Forum.Name, Constants.Applications.Forum.Actions.Thread, id, 1));
            }

            return View("Thread", _forumViewService.GetThread(id, pageNumber));
        }

        public ViewResult Section(long id)
        {
            return View("Section", _forumViewService.GetSection(id));
        }
    }
}
